package com.sy.bean;

import com.alibaba.fastjson.JSON;
import com.sy.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class HttpOperation {
    @Autowired(required = false)
    private HttpServletResponse res;

    public void writeJson(Integer code, String error) {
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter pw = null;
        try {
            pw = res.getWriter();
            Result result = new Result();
            result.setCode(code);
            result.setError(error);
            res.setStatus(code);
            pw.print(JSON.toJSONString(result, true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeJson(Integer code, Object data) {
        res.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter pw = null;
        try {
            pw = res.getWriter();
            Result result = new Result();
            result.setCode(code);
            result.setData(data);
            res.setStatus(code);
            pw.print(JSON.toJSONString(result, true));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
